#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/epoll.h>
#include "Log.hpp"

const static int gsize = 128;
const static int defaultepfd = -1;

namespace EpollerModule
{
    class Epoller
    {
    public:
        Epoller(): _epfd(defaultepfd)
        {}
        void InitEpoller()
        {
            _epfd = epoll_create(gsize);
            if(_epfd == defaultepfd)
            {
                lg.LogMessage(Error, "epoll_create failed, %s : %d", strerror(errno), errno);
                exit(1);
            }
            lg.LogMessage(Info, "create epoll success, epollfd: %d", _epfd);
        }
        void AddEvent(int sockfd, uint32_t events)
        {
            struct epoll_event ev;
            ev.events = events;
            ev.data.fd = sockfd; // 这个fd不是给内核的，作用是什么?
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
            if(n < 0)
            {
                lg.LogMessage(Error, "epoll_ctl add failed, %s : %d", strerror(errno), errno);
            }
        }
        int Wait(struct epoll_event* recvs, int maxevents, int timeout)
        {
            int n = epoll_wait(_epfd, recvs, maxevents, timeout);
            return n;
        }
        ~Epoller()
        {
            if(_epfd >= 0)
            {
                close(_epfd);
            }
            lg.LogMessage(Info, "close epollfd success");
        }
    private:
        int _epfd;
    };
}